<template>
  <section class="todoapp">
    <hm-header @add="Add"></hm-header>
    <hm-main :list="showList"
             @del="Del"
             @Change="ChangeF"
             @changeAll="changeAll"></hm-main>
    <hm-footer @changeType="changeType" 
               :list="list"
               @clear="clear"
               :type="type"></hm-footer>
  </section>
</template>

<script>
import HmHeader from "./components/hm-header.vue";
import HmMain from "./components/hm-main.vue";
import HmFooter from "./components/hm-footer.vue";
export default {
  data () {
    return {
      list:JSON.parse(localStorage.getItem('todoList'))|| [
        { id: 1, name: '抽烟', flag: false },
        { id: 2, name: '喝酒', flag: true },
        { id: 3, name: '烫头', flag: false },
      ],
      type: 'all'
    }
  },
  components: {
    HmHeader,
    HmMain,
    HmFooter,
  },
  methods: {
    Del (id) {
      this.list = this.list.filter(item => item.id !== id)
    },
    Add (newName) {
      this.list.unshift({
        id: +new Date(),
        name: newName,
        flag: false,
      })
    },
    ChangeF (flag, id) {
      // console.log(flag,id);
      this.list.find(item => item.id === id).flag = flag
    },
    //不传flag的情况
    // ChangeF(id){
    //   // console.log(flag,id);
    //   this.list.find(item=>item.id===id).flag = !(flag=this.list.find(item=>item.id===id).flag)
    // },
    clear () {
      this.list = this.list.filter(item => item.flag === false)
    },
    changeType(type) {
      this.type=type
    },
    changeAll(flag){
      this.list.forEach(item=>item.flag=flag)
    }
  },
  computed:{
    showList(){
      if (this.type==='all') {
        return this.list
      }else if (this.type==='active') {
        return this.list.filter(item=>!item.flag)
      }else {
        return this.list.filter(item=>item.flag)
      }
    }
  },
  watch:{
    list:{
      deep:true,
      handler(newVal){
        localStorage.setItem('todoList',JSON.stringify(newVal))
      }
    }
  }
}
</script>

<style scoped>
</style>
